<!--//This file is part of the store/retrieve project
//    (http://code.google.com/p/storeretrieve/).
//
//    Store/retrieve is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Store/retrieve is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with store/retrieve. If not, see <http://www.gnu.org/licenses/>.
//-->


<%@ page
	import="java.util.Properties,
		java.util.ArrayList,
		java.io.File,
		java.io.FileInputStream,
		org.w3c.dom.*,
		javax.xml.parsers.*,
		javax.xml.xpath.*,
		java.util.HashMap,
		java.lang.StringBuilder"%>

<%!
ArrayList<File> query(String path, HashMap<String, String> queryParms) {
		ArrayList<File> result = new ArrayList<File>();
		ArrayList<File> allMetaFiles = new ArrayList<File>();
		File[] yearLevel = new File(path).listFiles();
		for(File year : yearLevel) {
			if(year.isDirectory()) {
				File[] monthLevel = year.listFiles();
					for(File month : monthLevel) {
						if(month.isDirectory()) {
							File[] dayLevel = month.listFiles();
								for(File day : dayLevel) {
									if(day.isDirectory()) {
										File[] containerLevel = day.listFiles();
											for(File container : containerLevel) {
												if(container.isDirectory()) {
													if(new File(container.getAbsolutePath() + "/meta.xml").exists())
														allMetaFiles.add(container);
												}
											}
									}
								}
						}
					}
			}
		}

		for(File metaXml : allMetaFiles) {
			boolean doesMatch = true;
			try {
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
				Document doc = dBuilder.parse(new File(metaXml.getAbsolutePath() + "/meta.xml"));
				doc.getDocumentElement().normalize();
				for(Object key : queryParms.keySet()) {
					XPath xpath = XPathFactory.newInstance().newXPath();
					XPathExpression expr = xpath.compile("/Container/" + (key));
					NodeList nodes = (NodeList)(expr.evaluate(doc, XPathConstants.NODESET));
					if(nodes == null || nodes.getLength() == 0)  {
						doesMatch = false;

					} else {
						String textContent = nodes.item(0).getTextContent();
						if(textContent == null || !textContent.matches(queryParms.get(key)))
							doesMatch = false;
					}
				}
			} catch(Throwable ex) { 
				 doesMatch = false; 
				 ex.printStackTrace();
			} finally {}
			
			if(doesMatch)
				result.add(metaXml);
		}

		return result;
	}
%>
